<?php

namespace App\Repositories\Permission;

use App\Models\Admin;
use App\Repositories\BaseRepository;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;

class AdminRepository extends BaseRepository
{
    public function __construct(Admin $model)
    {
        parent::__construct($model);
    }

    public function getByPhone($phone): ?Admin
    {
        return Admin::query()->where('phone', $phone)->first();
    }

    public function getByEmail($email): ?Admin
    {
        return Admin::query()->where('email', $email)->first();
    }

    public function login($phone, $password, $remember = false): string
    {
        $admin = Admin::query()->where('phone', $phone)->first();
        if (! $admin) {
            abort(403, '账号或者密码错误,请核对后再重新登录');
        }

        if (! password_verify($password, $admin->password)) {
            abort(403, '账号或者密码错误,请核对后再重新登录');
        }

        if ($admin->status != 1) {
            abort(403, '该账号已被禁用,请联系管理员');
        }
        auth('admin')->login($admin, $remember);

        return $admin;
    }

    public function paginate(array $params = []): LengthAwarePaginator
    {
        $query = Admin::query();
        if ($name = Arr::get($params, 'name')) {
            $query->where('name', 'like', '%'.$name.'%');
        }
        if ($phone = Arr::get($params, 'phone')) {
            $query->where('phone', $phone);
        }
        if ($email = Arr::get($params, 'email')) {
            $query->where('email', $email);
        }
        $startDate = Arr::get($params, 'startDate');
        $endDate = Arr::get($params, 'endDate');
        if ($startDate && $endDate) {
            $query->whereBetween('created_at', [$startDate, $endDate]);
        }

        return $query->orderByDesc('id')->paginate(10)->through(fn (Admin $item) => [
            'id' => $item->id,
            'name' => $item->name,
            'phone' => $item->phone,
            'email' => $item->email,
            'avatar' => $item->avatar ?? '',
            'status' => $item->status,
            'is_super' => $item->is_super,
            'roles' => $item->getRoleNames(),
            'created_at' => $item->created_at->format('Y-m-d'),
        ]);
    }
}
